package com.example.mychat.webSocket;

import com.example.mychat.entity.dto.MessageSendDto;
import com.example.mychat.entity.po.ChatMessage;
import com.example.mychat.redis.RedisComponent;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @Description
 * @Author susu
 * @Date 2025/4/14
 */
@Component
public class DelayedMessageListener implements ChannelAwareMessageListener {
    @Resource
    private MessagePublisher messagePublisher;
    @Resource
    private RedisComponent redisComponent;

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        String QueueName = message.getMessageProperties().getConsumerQueue();
        String userId = extractUserIdFromQueue(QueueName);
        String content = new String(message.getBody());
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            MessageSendDto messageSendDto = objectMapper.readValue(message.getBody(), MessageSendDto.class);
            if (redisComponent.getUserOnline(userId)){
                if (redisComponent.acquireLock(userId,QueueName)){
                    messagePublisher.sendMsg(messageSendDto);
                    redisComponent.saveMessageId(String.valueOf(messageSendDto.getMessageId()),userId);
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                }
            }else{
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            redisComponent.unlock(userId,QueueName);
        }
    }

    private String extractUserIdFromQueue(String queueName) {
        StringBuilder str = new StringBuilder();

        return queueName.replace("user_", "").replace("_queue", "");
    }
}
